<?php
/* ************************************************** *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: {creation_date}
 * @project		: 
 * @description	: {description}
 *		- 
 *
\* ************************************************** */
class Employee extends MY_Controller {
    
    function __construct( ) {
        parent::__construct( );
		$this->load->model( 'CodeGenerator_model', '', TRUE );
		$this->load_template();
	}	
	
	function index( ){
		$this->manage( );
	}
    
    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Manage list
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function manage( ){
		$role = $this->session->userdata('role');
		$filter = $this->input->get('filter');
		$orderby = $this->input->get('orderby');
		//paging
        $config['base_url'] = base_url().'employee/manage/';
		if($filter) {$config['suffix'] = "/?filter=$filter&orderby=$orderby";
			$config['first_url'] = $config['base_url']."0/?filter=$filter&orderby=$orderby";
		}

        $config['total_rows'] = $this->CodeGenerator_model->count("employee");
        $config['per_page'] = PER_PAGE;	
       
		$start = $this->uri->segment(3);
		if(empty($start)) $start = 0;
		$perpage = $config['per_page'];
		$this->data['permit'] = $this->checkpermission();
		if(empty($filter)) $str_orderby = ''; else $str_orderby = "$filter $orderby";
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'employee_add' ];

		$rules                  =         array(
			array('field_id' => 'Name','label' => 'Tên','control' => 'Array','width' => '20%', 'class' => 'first border-right', 'style' => 'border-right: solid 3px #fff;'),
			array('field_id' => 'DOB','label' => 'Ngày sinh','control' => 'time','width' => '20%', 'class' => ' border-right', 'style' => 'border-right: solid 3px #fff;'),
			array('field_id' => 'Phone_NO','label' => 'Số đt','control' => 'Array','width' => '20%', 'class' => ' border-right', 'style' => 'border-right: solid 3px #fff;'),
			array('field_id' => 'Street','label' => 'Street','control' => 'Array','width' => '20%', 'class' => ' border-right', 'style' => 'border-right: solid 3px #fff;'),
			// array('field_id' => 'Position','label' => 'Chức vụ','control' => 'Array',),
			// array('field_id' => 'Hired_Dt','label' => 'Ngày kí hợp đồng','control' => 'time',),
			// array('field_id' => 'Term_Dt','label' => 'Ngày hết hợp đồng','control' => 'time',)
			);
       
		
        // Make header
        // --------------------------------------------------
        $header = array( );
        foreach( $rules as $k => $item ){
             $header[ ] = $item[ 'label' ];
			$str1='';$str2='';
			if($filter == $item['field_id']){
				if($orderby == "DESC") {$orderby = "ASC";$img1="display: none;";$img2="display: inline;"; } else {$orderby = "DESC";$img1="display: inline;";$img2="display: none;";}
				$url= base_url()."employee/manage/$start/?filter=$filter&orderby=$orderby";
				$str1 = 'onmouseout="$(\'.soimg2\').toggle()" onmouseover="$(\'.soimg2\').toggle()"';
				$str2='<img class="icon ic_s_asc soimg2" alt="Ascending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img1.'"> <img class="icon ic_s_desc soimg2 hide" alt="Descending" title="" src="'.base_url().'resources/images/dot.gif" style="'.$img2.'">';
			}else $url= base_url()."employee/manage/$start/?filter=".$item['field_id']."&orderby=ASC";
			$rules[$k]['html'] ='<span><a title="" '.$str1.' href="'.$url.'">'.$item[ 'label' ].' '.$str2.'</a></span>';
			if(isset($item['order'])&&!$item['order']) $rules[$k]['html'] = $item[ 'label' ];
        }
		
		 $this->data[ 'rules' ]  =   $rules;
		if($role == ADMINISTRATOR) 
        $this->data[ 'header' ] =   $header;
		if($role == ADMINISTRATOR) 
			$results                =   $this->CodeGenerator_model->get( 'employee', 'EE_ID,Personal_ID,Name,DOB,Salary,Phone_NO,Street,Position,Yrs_of_exp,Education_Level,Dichvu,Create_Dt,Hired_Dt,Term_Dt,Active,Delete' ,'role !='.ADMINISTRATOR, $config['per_page'],$start,false,"array", $str_orderby);
		else 
			$results                =   $this->CodeGenerator_model->get( 'employee', 'EE_ID,Personal_ID,Name,DOB,Phone_NO,Street,Position,Yrs_of_exp,Education_Level,Create_Dt,Hired_Dt,Term_Dt,Active,Delete','role !='.ADMINISTRATOR, $config['per_page'],$start,false,"array", $str_orderby );
        // Make action Edit/Delete
        // --------------------------------------------------
        for( $i = 0; $i < count( $results ); $i++ ){
	       $id = array_values( $results[ $i ]);
            $results[ $i ][ 'Edit'   ]   =  anchor( base_url( ) . 'index.php/employee/edit/' . $id[ 0 ], 'Edit');  
            $results[ $i ][ 'Delete' ]   =  anchor( 
                        base_url( ) . 'index.php/employee/delete/' . $id[ 0 ], 
                        'Delete',
                        array( 'onClick' => 'return deletechecked(\' ' . base_url() . 'index.php/employee/delete/' . $id[ 0 ] . ' \')' ) );                        
			if($results[$i]['Personal_ID']=="test") {unset($results[$i]); //ko hien user test
				$config['total_rows'] = $config['total_rows'] -1;
			}
        }
         $this->pagination->initialize($config); 
        $this->data[ 'results'        ]     =   $results;
		if($role == ADMINISTRATOR) 
			$this->data[ 'master_limited' ]     =   explode(',', 'EE_ID,Personal_ID,Name,DOB,Salary,Phone_NO,Street,Position,Yrs_of_exp,Education_Level,Dichvu,Create_Dt,Hired_Dt,Term_Dt,Active,Delete');
		else $this->data[ 'master_limited' ]     =   explode(',', 'EE_ID,Personal_ID,Name,DOB,Phone_NO,Street,Position,Yrs_of_exp,Education_Level,Create_Dt,Hired_Dt,Term_Dt,Active,Delete');
		if($this->data['permit'])
			$this->data[ 'action'         ]     =   array(array('id' => 'new','label' => 'Thêm nhân viên','url' => 'index.php/employee/add/',),array('id' => 'edit','label' => 'Edit','url' => 'index.php/employee/edit/',),array('id' => 'delete','label' => 'Delete','url' => '',),);
        // $this->load->view( 'employee_list', $this->data ); 
		$this->template->write( 'title', 'Spa - Nhân viên' );
		// $this->template->add_css( 'resources/css/users.css' );
        $this->template->write_view( 'content', 'employee_list.php',$this->data );
        $this->template->render();
    }
	
	public function Personal_ID_check($str)
	{
			$sql = "select EE_ID from employee where Personal_ID = '$str'";
			$result = $this->CodeGenerator_model->custom_query($sql);
			if(!empty($result)){
				$this->form_validation->set_message('Personal_ID_check', 'Tên đăng nhập đã tồn tại.');
				return false;
			}
			return true;
	}
	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Load form add new record
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
	

    function add( ){  
		$this->data[ 'custom_error' ] = '';
		$username = "noname";
		$role = $this->session->userdata('role');
		$userid = 0;
		$ee_id = $this->input->post('EE_ID');
		$per_id = $this->input->post('Personal_ID');
		if(!$ee_id)
			$ee_id="EE_".uniqid();
		$this->data['temp_id'] = $ee_id;
		$this->data['role'] = $role;
		
		$selected_cat=$this->input->post('Role');

		if(empty($selected_cat)) $selected_cat = '1';
		$combobox_cats['1']="Employer";
		
		$combobox_cats['3']="Administrator";
		
		$this->data['combobox_cats']=form_dropdown('Role', $combobox_cats,$selected_cat);
		
        if( $this->form_validation->run( 'employee_add' ) == false ){
             $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );
        }else{     
				$data = array(
						'EE_ID' => $ee_id,
						'Personal_ID' => $per_id,
						'Name' => set_value('Name'),
						'Password' => set_value('Password'),
						'DOB' => strtotime(str_replace(array("/"),array("."),set_value('DOB'))),
						'Phone_NO' => set_value('Phone_NO'),
						'Role' => $selected_cat,
						'Street' => set_value('Street'),
						'Position' => set_value('Position'),
						'Yrs_of_exp' => set_value('Yrs_of_exp'),
						'Education_Level' => set_value('Education_Level'),
						'Create_Dt' => time(),
						'Hired_Dt' => strtotime(str_replace(array("/"),array("."),set_value('Hired_Dt'))),
						'Term_Dt' => strtotime(str_replace(array("/"),array("."),set_value('Term_Dt'))),
						'Active' => set_value('Active'),
						'Dichvu' => set_value('Dichvu')
				);
				if($role == ADMINISTRATOR) $data['Salary'] = set_value('Salary');
				$result = $this->CodeGenerator_model->add( 'employee', $data, 'EE_ID' );
				if( $result == ADD_SUCCESSFULLY ){
					redirect( base_url() . 'index.php/employee' );
				}else if( $result == RECORD_EXISTED ){
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>A record existed.</p></div>';
				}else{
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured.</p></div>';
				}
		}		   
		// $this->load->view( 'employee_add', $this->data );   
		$this->template->write( 'title', 'Spa - Thêm nhân viên' );
        $this->template->write_view( 'content', 'employee_add.php',$this->data );
        $this->template->render();
    }	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Load edit form.
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function edit( ){
        $this->data[ 'custom_error' ] = '';
		$role = $this->session->userdata('role');
		$this->data['role'] = $role;
		$username = "noname";
		$userid = 0;

        if( $this->form_validation->run( 'employee_edit' ) == false ){
            $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );

        }else{  
			$this->form_validation->set_rules('Phone_NO', 'Phone_NO', 'callback_Phone_Number_check');
			if ($this->form_validation->run('employee_edit') == false)
			{
				 $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
			}
			else{
			   $data = array(
					'Personal_ID' => $this->input->post('Personal_ID'),
					'Name' => $this->input->post('Name'),
						'Password' => $this->input->post('Password'),
						'DOB' => strtotime(str_replace(array("/"),array("."),$this->input->post('DOB'))),
						'Phone_NO' => $this->input->post('Phone_NO'),
						'Street' => $this->input->post('Street'),
						'Role' => $this->input->post('Role'),
						'Position' => $this->input->post('Position'),
						'Yrs_of_exp' => $this->input->post('Yrs_of_exp'),
						'Education_Level' => $this->input->post('Education_Level'),
						'Hired_Dt' => strtotime(str_replace(array("/"),array("."),$this->input->post('Hired_Dt'))),
						'Term_Dt' => strtotime(str_replace(array("/"),array("."),$this->input->post('Term_Dt'))),
						'Active' => $this->input->post('Active'),
						'Dichvu' => $this->input->post('Dichvu')
				);
				if($role == ADMINISTRATOR) $data['Salary'] = $this->input->post('Salary');
				if( $this->CodeGenerator_model->edit( 'employee', $data, 'EE_ID', $this->input->post( 'EE_ID' ) ) == TRUE ){
					redirect( base_url( ) . 'index.php/employee/manage/' );
				}else{
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured</p></div>';
				}
			}
		}
		$result   =   $this->CodeGenerator_model->get( 'employee', 'EE_ID,Personal_ID,Name,Password,DOB, Salary,Role,Phone_NO,Street,Position,Yrs_of_exp,Education_Level,Create_Dt,Hired_Dt,Term_Dt,Active,Dichvu,Delete', 'EE_ID = "' . $this->uri->segment( 3 ) . '"', NULL, NULL, true );  
		// $this->load->view( 'employee_edit', $this->data );		
		$selected_cat=$this->input->post('Role');
		
		if(empty($selected_cat)) $selected_cat = '1';
		$combobox_cats['1']="Employer";
		if(!empty($result)) $selected_cat = $result->Role;
		$combobox_cats['3']="Administrator";
		$this->data['result'] = $result;
		$this->data['combobox_cats']=form_dropdown('Role', $combobox_cats,$selected_cat);
		$this->template->write( 'title', 'Spa - Sửa nhân viên' );
        $this->template->write_view( 'content', 'employee_edit.php',$this->data );
        $this->template->render();
    }
	function myprofile( ){
        $this->data[ 'custom_error' ] = '';
		$username = "noname";
		$userid = 0;

        if( $this->form_validation->run( 'employee_edit' ) == false ){
            $this->data[ 'custom_error' ] = ( validation_errors( ) ? '<div class="form_error">' . validation_errors( ) . '</div>' : false );

        }else{  
			$this->form_validation->set_rules('Phone_NO', 'Phone_NO', 'callback_Phone_Number_check');
			if ($this->form_validation->run('employee_edit') == false)
			{
				 $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
			}
			else{
			   $data = array(
						'Personal_ID' => $this->input->post('Personal_ID'),
						'Password' => $this->input->post('Password'),
						'DOB' => strtotime(str_replace(array("/"),array("."),$this->input->post('DOB'))),
						'Phone_NO' => $this->input->post('Phone_NO'),
						'Street' => $this->input->post('Street'),
						'Position' => $this->input->post('Position'),
						'Yrs_of_exp' => $this->input->post('Yrs_of_exp'),
						'Education_Level' => $this->input->post('Education_Level'),
						'Hired_Dt' => strtotime(str_replace(array("/"),array("."),$this->input->post('Hired_Dt'))),
						'Term_Dt' => strtotime(str_replace(array("/"),array("."),$this->input->post('Term_Dt')))
				);
				if( $this->CodeGenerator_model->edit( 'employee', $data, 'EE_ID', $this->input->post( 'EE_ID' ) ) == TRUE ){
					redirect( base_url( ) . 'index.php/employee/myprofile/'.$this->uri->segment( 3 ) );
				}else{
					$this->data[ 'custom_error' ] = '<div class="form_error"><p>An Error Occured</p></div>';
				}
			}
		}
		$this->data[ 'result' ]   =   $this->CodeGenerator_model->get( 'employee', 'EE_ID,Personal_ID,Password,DOB,Phone_NO,Street,Position,Yrs_of_exp,Education_Level,Create_Dt,Hired_Dt,Term_Dt,Active,Delete', 'Personal_ID = "' . $this->session->userdata('username') . '"', NULL, NULL, true );  
		// $this->load->view( 'employee_edit', $this->data );		
		$this->template->write( 'title', 'Spa - Thông tin tài khoản' );
        $this->template->write_view( 'content', 'myprofile.php',$this->data );
        $this->template->render();
    }
	
	

    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Delete record
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
    function delete( ){
        $ID =  $this->uri->segment( 3 );
        $this->CodeGenerator_model->delete(  'employee', 'EE_ID', $ID );             
        redirect( base_url( ) . 'index.php/employee/manage/' );
    }       
}